package org.lw.springbootlw.auth.service.impl;

import org.lw.springbootlw.common.mapper.auth.UserMapper;
import org.lw.springbootlw.common.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper; // 假设你有一个 UserMapper 用于访问用户数据
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库中查询用户
        Optional<User> userOptional = userMapper.findUserWithRolesByUsername(username);

        if (userOptional.isEmpty()) {
            throw new UsernameNotFoundException("User not found with username: " + username);
        }

        User user = userOptional.get();
        System.out.println("User found: " + user);
        System.out.println(user.getPassword());
        // 返回实现了 UserDetails 接口的对象
        // roles 里面有权限信息，需要转换成 SimpleGrantedAuthority 对象

        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                Stream.concat(
                        user.getRoles().stream()
                                .map(role -> new SimpleGrantedAuthority("ROLE_" + role.getRoleName())), // 添加角色
                        user.getRoles().stream()
                                .flatMap(role -> role.getPermissions().stream()
                                        .map(permission -> new SimpleGrantedAuthority(permission.getPermissionName())) // 添加权限
                                )
                ).collect(Collectors.toList())
        );

    }
}

